<template>
  <div class="medicine-order-manage-container">
    <h2 class="page-title">药品订单管理</h2>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <el-input 
            v-model="queryParams.orderSearch" 
            placeholder="输入订单号或用户名" 
            clearable 
            @keyup.enter="handleQuery"
          />
        </div>
        
        <div class="filter-item date-range">
          <span class="label">日期</span>
          <el-date-picker
            v-model="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
          <span class="separator">—</span>
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <el-button type="primary" @click="handleQuery">筛选</el-button>
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <!-- 标签页 -->
      <div class="tabs">
        <div 
          v-for="(tab, index) in tabs" 
          :key="index" 
          :class="['tab-item', {'active': queryParams.status === tab.value}]"
          @click="handleTabChange(tab.value)"
        >
          {{ tab.label }}
        </div>
      </div>
      
      <!-- 表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="orderList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="orderNo" label="订单编号" align="center" width="150" />
          <el-table-column label="提交时间" align="center" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.submitTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="userPhone" label="用户名" align="center" />
          <el-table-column prop="receiver" label="收货人" align="center" />
          <el-table-column label="订单金额" align="center">
            <template #default="scope">
              {{ scope.row.orderAmount }} 元
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button type="primary" link @click="handleView(scope.row)">查看订单</el-button>
              
              <!-- 根据订单状态显示不同操作按钮 -->
              <template v-if="scope.row.status === '待发货'">
                <el-button type="success" link @click="handleShip(scope.row)">订单发货</el-button>
              </template>
              
              <template v-if="scope.row.status === '待收货'">
                <el-button type="warning" link @click="handleConfirmReceive(scope.row)">确认收货</el-button>
              </template>
              
              <template v-if="scope.row.status === '已收货'">
                <el-button type="info" link @click="handleTrack(scope.row)">订单追踪</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <div class="page-info">
          共{{ totalCount }}条数据
        </div>
        <el-pagination
          v-model:current-page="queryParams.pageIndex"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 查看订单对话框 -->
    <el-dialog v-model="dialogVisible" :title="getDialogTitle()" width="800px" destroy-on-close>
      <div v-if="orderDetail" v-loading="detailLoading" class="order-detail">
        <div class="detail-section">
          <h3 class="section-title">订单信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">订单编号：</span>
              <span>{{ orderDetail.orderNo }}</span>
            </div>
            <div class="detail-item">
              <span class="label">提交时间：</span>
              <span>{{ formatDateTime(orderDetail.submitTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">订单金额：</span>
              <span class="amount">￥{{ orderDetail.orderAmount }}</span>
            </div>
            <div class="detail-item">
              <span class="label">订单状态：</span>
              <span>
                <el-tag :type="getStatusType(orderDetail.status)">
                  {{ orderDetail.status }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h3 class="section-title">收货信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">收货人：</span>
              <span>{{ orderDetail.receiver?.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">联系电话：</span>
              <span>{{ orderDetail.receiver?.phone }}</span>
            </div>
            <div class="detail-item full-width">
              <span class="label">收货地址：</span>
              <span>{{ orderDetail.receiver?.address }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h3 class="section-title">药品清单</h3>
          <div v-if="orderDetail.medicines && orderDetail.medicines.length > 0" class="medicine-list">
            <div v-for="(medicine, index) in orderDetail.medicines" :key="index" class="medicine-item">
              <div class="medicine-image">
                <div class="rx-tag">Rx</div>
                <el-image 
                  v-if="medicine.imageUrl" 
                  :src="medicine.imageUrl" 
                  :preview-src-list="[medicine.imageUrl]"
                  style="width: 70px; height: 70px"
                  fit="cover"
                />
                <div v-else class="no-image">无图片</div>
              </div>
              <div class="medicine-info">
                <div class="medicine-name">{{ medicine.name }}</div>
                <div class="medicine-spec">规格：{{ medicine.specification }}</div>
                <div class="medicine-quantity">数量：{{ medicine.quantity }}</div>
                <div class="medicine-usage">用法：{{ medicine.usage }}</div>
              </div>
            </div>
          </div>
          <div v-else class="empty-medicines">暂无药品数据</div>
        </div>
        
        <!-- 根据订单状态显示不同的内容 -->
        <div v-if="orderDetail.status !== '待发货' && orderDetail.logistics" class="detail-section">
          <h3 class="section-title">物流信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">物流公司：</span>
              <span>{{ orderDetail.logistics.company }}</span>
            </div>
            <div class="detail-item">
              <span class="label">物流单号：</span>
              <span>{{ orderDetail.logistics.trackingNumber }}</span>
            </div>
          </div>
          
          <div v-if="orderDetail.logistics.trackingRecords && orderDetail.logistics.trackingRecords.length > 0" class="tracking-section">
            <div v-for="(record, index) in orderDetail.logistics.trackingRecords" :key="index" class="tracking-item">
              <div class="tracking-time">{{ formatDateTime(record.time) }}</div>
              <div class="tracking-content">{{ record.description }}</div>
            </div>
          </div>
          <div v-else class="no-tracking">
            暂无物流追踪记录
          </div>
          
          <div class="tracking-action">
            <el-button type="primary" @click="handleViewFullLogistics(orderDetail.orderNo)">查看完整物流</el-button>
          </div>
        </div>
        
        <div class="detail-section">
          <h3 class="section-title">订单操作</h3>
          <div class="action-buttons">
            <template v-if="orderDetail.status === '待发货'">
              <el-button type="success" @click="handleShip(orderDetail)">订单发货</el-button>
            </template>
            
            <template v-if="orderDetail.status === '待收货'">
              <el-button type="warning" @click="handleConfirmReceive(orderDetail)">确认收货</el-button>
              <el-button type="primary" @click="handleViewFullLogistics(orderDetail.orderNo)">查看物流</el-button>
            </template>
            
            <template v-if="orderDetail.status === '已收货'">
              <el-button type="primary" @click="handleViewFullLogistics(orderDetail.orderNo)">订单追踪</el-button>
            </template>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物流追踪对话框 -->
    <el-dialog v-model="logisticsDialogVisible" title="物流追踪详情" width="700px" destroy-on-close>
      <div v-if="logisticsDetail" v-loading="logisticsLoading" class="logistics-detail">
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">订单编号：</span>
              <span>{{ logisticsDetail.orderNo }}</span>
            </div>
            <div class="detail-item">
              <span class="label">物流公司：</span>
              <span>{{ logisticsDetail.logisticsCompany }}</span>
            </div>
            <div class="detail-item">
              <span class="label">运单编号：</span>
              <span>{{ logisticsDetail.trackingNumber }}</span>
            </div>
            <div class="detail-item">
              <span class="label">收货人：</span>
              <span>{{ logisticsDetail.receiver }}</span>
            </div>
            <div class="detail-item full-width">
              <span class="label">收货地址：</span>
              <span>{{ logisticsDetail.receiveAddress }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h3 class="section-title">物流追踪</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in logisticsDetail.trackingItems"
              :key="index"
              :timestamp="formatDateTime(activity.time)"
              :type="index === 0 ? 'primary' : ''"
              :hollow="index !== 0"
            >
              <div class="timeline-location">{{ activity.location }}</div>
              <div class="timeline-detail">{{ activity.detail }}</div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logisticsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { axiosrzsh } from '@/http/axiosRead'

// 定义药品订单的接口类型
interface MedicineOrder {
  orderNo: string
  submitTime: string
  userPhone: string
  receiver: string
  orderAmount: number
  status: string
}

// 收货人信息
interface Receiver {
  name: string
  phone: string
  address: string
}

// 药品详情
interface MedicineDetail {
  name: string
  imageUrl: string
  specification: string
  usage: string
  quantity: number
}

// 物流记录项
interface TrackingRecord {
  time: string
  description: string
}

// 物流信息
interface Logistics {
  company: string
  trackingNumber: string
  trackingRecords: TrackingRecord[]
}

// 药品订单详情
interface MedicineOrderDetail {
  orderNo: string
  orderAmount: number
  status: string
  submitTime: string
  receiver: Receiver
  medicines: MedicineDetail[]
  logistics?: Logistics
}

// 物流追踪项
interface TrackingItem {
  time: string
  location: string
  detail: string
}

// 物流详情
interface LogisticsDetail {
  orderNo: string
  logisticsCompany: string
  trackingNumber: string
  receiver: string
  receiveAddress: string
  trackingItems: TrackingItem[]
}

// 定义查询参数
const queryParams = reactive({
  orderSearch: '',
  startTime: '',
  endTime: '',
  status: 0, // 默认查询全部
  pageIndex: 1,
  pageSize: 10
})

// 标签页配置
const tabs = [
  { label: '全部', value: 0 },
  { label: '待发货', value: 1 },
  { label: '待收货', value: 2 },
  { label: '已收货', value: 3 }
]

// 数据列表
const orderList = ref<MedicineOrder[]>([])
const totalCount = ref(0)
const totalPage = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const currentOrder = ref<MedicineOrder | null>(null)

// 添加新的状态变量
const orderDetail = ref<MedicineOrderDetail | null>(null)
const detailLoading = ref(false)
const logisticsDialogVisible = ref(false)
const logisticsDetail = ref<LogisticsDetail | null>(null)
const logisticsLoading = ref(false)

// 获取药品订单列表
const getMedicineOrderList = async () => {
  loading.value = true
  try {
    const response = await axiosrzsh.get('/MedicineOrder', {
      params: queryParams
    })
    if (response.data.code === 200) {
      orderList.value = response.data.pageData || []
      totalCount.value = response.data.totaCount || 0
      totalPage.value = response.data.totaPage || 0
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取药品订单数据失败:', error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string): string => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 获取状态样式类型
const getStatusType = (status: string): string => {
  switch (status) {
    case '待发货':
      return 'warning'
    case '待收货':
      return 'primary'
    case '已收货':
      return 'success'
    default:
      return 'info'
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageIndex = 1
  getMedicineOrderList()
}

// 处理标签页切换
const handleTabChange = (status: number) => {
  queryParams.status = status
  handleQuery()
}

// 处理分页大小改变
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  getMedicineOrderList()
}

// 处理分页页码改变
const handleCurrentChange = (page: number) => {
  queryParams.pageIndex = page
  getMedicineOrderList()
}

// 获取对话框标题
const getDialogTitle = (): string => {
  if (!orderDetail.value) return '订单详情'
  return `订单详情 - ${orderDetail.value.status}`
}

// 修改处理查看详情
const handleView = async (row: MedicineOrder) => {
  dialogVisible.value = true
  detailLoading.value = true
  try {
    const response = await axiosrzsh.get(`/MedicineOrder/${row.orderNo}`)
    if (response.data.code === 200) {
      orderDetail.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请检查网络连接')
  } finally {
    detailLoading.value = false
  }
}

// 修改处理发货方法
const handleShip = (row: MedicineOrder | MedicineOrderDetail) => {
  ElMessageBox.confirm('确认发货此订单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里添加发货API调用
    ElMessage.success('订单发货成功')
    getMedicineOrderList()
  }).catch(() => {})
}

// 修改处理确认收货方法
const handleConfirmReceive = (row: MedicineOrder | MedicineOrderDetail) => {
  ElMessageBox.confirm('确认此订单已收货?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里添加确认收货API调用
    ElMessage.success('确认收货成功')
    getMedicineOrderList()
  }).catch(() => {})
}

// 处理订单追踪
const handleTrack = (row: MedicineOrder) => {
  handleViewFullLogistics(row.orderNo)
}

// 处理查看完整物流
const handleViewFullLogistics = async (orderNo: string) => {
  logisticsDialogVisible.value = true
  logisticsLoading.value = true
  try {
    const response = await axiosrzsh.get(`/MedicineOrder/logistics/${orderNo}`)
    if (response.data.code === 200) {
      logisticsDetail.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取物流信息失败')
    }
  } catch (error) {
    console.error('获取物流信息失败:', error)
    ElMessage.error('获取物流信息失败，请检查网络连接')
  } finally {
    logisticsLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  getMedicineOrderList()
})
</script>

<style scoped>
.medicine-order-manage-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f7f7f7;
  border-radius: 5px;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-item {
  margin-right: 15px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.filter-item .label {
  margin-right: 8px;
  white-space: nowrap;
}

.date-range {
  display: flex;
  align-items: center;
}

.separator {
  margin: 0 8px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-info {
  color: #666;
}

.order-detail {
  padding: 10px 0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.detail-section {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  border-radius: 5px;
  padding: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  line-height: 24px;
}

.detail-item .label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.full-width {
  grid-column: 1 / -1; /* 跨两列 */
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.medicine-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.medicine-item {
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.medicine-image {
  width: 70px;
  height: 70px;
  position: relative;
  margin-right: 15px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  overflow: hidden;
}

.rx-tag {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #f56c6c;
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 0 0 4px 0;
  z-index: 1;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.medicine-info {
  flex: 1;
}

.medicine-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.medicine-spec, .medicine-quantity, .medicine-usage {
  color: #606266;
  font-size: 13px;
  margin-bottom: 3px;
}

.empty-medicines {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.tracking-section {
  margin-top: 15px;
  border-top: 1px dashed #dcdfe6;
  padding-top: 15px;
}

.tracking-item {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.tracking-time {
  font-size: 13px;
  color: #909399;
  margin-bottom: 5px;
}

.tracking-content {
  color: #303133;
}

.no-tracking {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.tracking-action {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.timeline-location {
  font-weight: bold;
  margin-bottom: 5px;
}

.timeline-detail {
  color: #606266;
}
</style> 